package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	engine := gin.Default()
	engine.POST("/login", loginV1)
	engine.POST("/loginV2", loginV2)
	engine.POST("/loginV3", loginV3)
	engine.Run()
}

// curl -X POST "http://localhost:8080/login"
// curl -X POST "http://localhost:8080/login?username=zhangsan&password=111111"
// curl -X POST -d 'username=zhangsan&password=111111' "http://localhost:8080/login"
func loginV1(ctx *gin.Context) {
	username := ctx.PostForm("username")
	password := ctx.DefaultPostForm("password", "123456")	//请求参数带默认值
	ctx.JSON(http.StatusOK, gin.H{
		"username": username,
		"password": password,
	})
}
// curl -X POST "http://localhost:8080/loginV2?username=zhangsan&password=111111"
// curl -X POST -d 'username=zhangsan&password=111111' "http://localhost:8080/loginV2"
func loginV2(ctx *gin.Context) {
	var req LoginReq
	err := ctx.ShouldBind(&req)
	if err != nil {
		fmt.Println("error happened.", err)
		ctx.String(http.StatusOK, "system error")
		return
	}
	ctx.String(http.StatusOK, fmt.Sprintf("username=%s, password=%s\n", req.Username, req.Password))
}

//接收json请求
// curl -H "Content-Type:application/json" -X POST -d '{"username":"zhangsan","password":"111111"}' "http://localhost:8080/loginV3"
func loginV3(ctx *gin.Context) {
	var req LoginReq
	err := ctx.ShouldBind(&req)
	// 如果想多次绑定，使用
	//ctx.ShouldBindBodyWith(&req, binding.JSON)
	if err != nil {
		fmt.Println("error happened.", err)
		ctx.String(http.StatusOK, "system error")
		return
	}
	ctx.String(http.StatusOK, fmt.Sprintf("username=%s, password=%s\n", req.Username, req.Password))
}

type LoginReq struct {
	Username string `json:"username" form:"username" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
}